package com.springboot.config.generator;

import com.springboot.config.tool.SpringUtil;
import com.springboot.project.common.dao.ModuleDao;
import com.springboot.project.common.dao.RolemoduleDao;
import com.springboot.project.common.entity.Module;
import com.springboot.project.common.entity.Rolemodule;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.*;
import java.util.*;

import static org.apache.commons.lang.time.DateFormatUtils.format;

/**
 * Created with IntelliJ IDEA.
 * User: lby.
 * Date: 2018/6/18.
 * Version: V1.0.
 */
public class GenUtils {

    public static Map<String,String> getTemplates(String javaPath, String htmlPath, String jsPath, String mapperPath, String domainName, String domainname) {
        Map<String,String> templates = new HashedMap();
        templates.put("generatorTemplate/Entity.java.vm",javaPath + "/entity/" + domainName + ".java");
        templates.put("generatorTemplate/Controller.java.vm",javaPath + "/controller/" + domainName + "Controller.java");
        templates.put("generatorTemplate/Service.java.vm",javaPath + "/service/" + domainName + "Service.java");
        templates.put("generatorTemplate/ServiceImpl.java.vm",javaPath + "/service/impl/" + domainName + "ServiceImpl.java");
        templates.put("generatorTemplate/Dao.java.vm",javaPath + "/dao/" + domainName + "Dao.java");

        templates.put("generatorTemplate/page.html.vm",htmlPath + "/" + domainname + "/" + domainname + ".html");
        templates.put("generatorTemplate/add.html.vm",htmlPath + "/" + domainname + "/" + domainname + "_add.html");
        templates.put("generatorTemplate/edit.html.vm",htmlPath + "/" + domainname + "/" + domainname + "_edit.html");
        templates.put("generatorTemplate/page.js.vm",jsPath + "/" + domainname + "/" + domainname + ".js");
        templates.put("generatorTemplate/add.js.vm",jsPath + "/" + domainname + "/"+ domainname + "_add.js");
        templates.put("generatorTemplate/edit.js.vm",jsPath + "/" + domainname + "/" + domainname + "_edit.js");

        templates.put("generatorTemplate/Mapper.xml.vm",mapperPath+ "/" +domainName + "Dao.xml");

        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns) {
        //配置信息
        Configuration config = getConfig();
        String targetPath = config.getString("targetPath");
        String javaPath = config.getString("javaPath");
        String mapperPath = config.getString("mapperPath");
        String htmlPath = config.getString("htmlPath");
        String jsPath = config.getString("jsPath");

        //表信息
        TableDO tableDO = new TableDO();
        tableDO.setTableName(table.get("tableName"));
        tableDO.setComments(table.get("tableComment"));
        //表名转换成Java类名
        String className = tableToJava(tableDO.getTableName(), config.getString("tablePrefix"), config.getString("autoRemovePre"));
        tableDO.setClassName(className);
        tableDO.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnDO> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnDO columnDO = new ColumnDO();
            columnDO.setColumnName(column.get("columnName"));
            columnDO.setDataType(column.get("dataType"));
            columnDO.setComments(column.get("columnComment"));
            columnDO.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnDO.getColumnName());
            columnDO.setAttrName(attrName);
            columnDO.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnDO.getDataType(), "unknowType");
            columnDO.setAttrType(attrType);

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableDO.getPk() == null) {
                tableDO.setPk(columnDO);
            }

            columsList.add(columnDO);
        }
        tableDO.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (tableDO.getPk() == null) {
            tableDO.setPk(tableDO.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties pro = new Properties();
        pro.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        pro.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        VelocityEngine ve = new VelocityEngine(pro);

        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableDO.getTableName());
        map.put("comments", tableDO.getComments());
        map.put("pk", tableDO.getPk());
        map.put("className", tableDO.getClassName());
        map.put("classname", tableDO.getClassname());
        map.put("pathName", config.getString("package").substring(config.getString("package").lastIndexOf(".") + 1));
        map.put("columns", tableDO.getColumns());
        map.put("package", config.getString("package"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", format(new Date(), "yyyy-MM-dd"));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        Map<String,String> templates = getTemplates(javaPath, htmlPath, jsPath, mapperPath, tableDO.getClassName(), tableDO.getClassname());
        for (String template : templates.keySet()) {
            String targetFile = (String) templates.get(template);
            //渲染模板
            Template tem = ve.getTemplate(template, "UTF-8");

            File file = new File(targetPath, targetFile);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                FileOutputStream outStream = new FileOutputStream(file);
                OutputStreamWriter writer = new OutputStreamWriter(outStream, "UTF-8");
                BufferedWriter sw = new BufferedWriter(writer);
                tem.merge(context, sw);
                sw.flush();
                sw.close();
                outStream.close();
                System.out.println("成功生成Java文件:" + (targetPath + targetFile).replaceAll("/", "\\\\"));
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        //新增菜单、新增超级管理员权限
        operDB(tableDO);
    }

    /**
     * 新增菜单、新增超级管理员权限
     */
    public static void operDB(TableDO tableDO)
    {
        Configuration config = getConfig();
        ModuleDao dao = SpringUtil.getBean(ModuleDao.class);
        RolemoduleDao rmDao = SpringUtil.getBean(RolemoduleDao.class);

        String code = tableDO.getClassname();
        String condition = String.format("code = '%s'",code);
        List<Module> list = dao.getListByCondition(condition);
        if(list.size() == 0) {
            //新增菜单
            Module listModule = new Module();
            listModule.setCode(tableDO.getClassname());
            listModule.setParentcode(config.getString("mainModule"));
            listModule.setParentcodes("[0],[" + config.getString("mainModule") + "],");
            listModule.setName(tableDO.getComments());
            listModule.setIcon("fa fa-user");
            listModule.setUrl("/" + tableDO.getClassname());
            listModule.setOrder(10);
            listModule.setLevels(2);
            listModule.setIsmenu(1);
            listModule.setStatus(1);
            listModule.setIsopen(1);

            Module addModule = new Module();
            addModule.setCode(tableDO.getClassname() + "_add");
            addModule.setParentcode(tableDO.getClassname());
            addModule.setParentcodes("[0],[" + config.getString("mainModule") + "],[" + tableDO.getClassname() + "],");
            addModule.setName("添加" + tableDO.getComments());
            addModule.setUrl("/" + tableDO.getClassname() + "/add");
            addModule.setOrder(1);
            addModule.setLevels(3);
            addModule.setIsmenu(0);
            addModule.setStatus(1);
            addModule.setIsopen(1);

            Module editModule = new Module();
            editModule.setCode(tableDO.getClassname() + "_edit");
            editModule.setParentcode(tableDO.getClassname());
            editModule.setParentcodes("[0],[" + config.getString("mainModule") + "],[" + tableDO.getClassname() + "],");
            editModule.setName("修改" + tableDO.getComments());
            editModule.setUrl("/" + tableDO.getClassname() + "/edit");
            editModule.setOrder(2);
            editModule.setLevels(3);
            editModule.setIsmenu(0);
            editModule.setStatus(1);
            editModule.setIsopen(1);

            Module delModule = new Module();
            delModule.setCode(tableDO.getClassname() + "_del");
            delModule.setParentcode(tableDO.getClassname());
            delModule.setParentcodes("[0],[" + config.getString("mainModule") + "],[" + tableDO.getClassname() + "],");
            delModule.setName("删除" + tableDO.getComments());
            delModule.setUrl("/" + tableDO.getClassname() + "/del");
            delModule.setOrder(3);
            delModule.setLevels(3);
            delModule.setIsmenu(0);
            delModule.setStatus(1);
            delModule.setIsopen(1);

            dao.insert(listModule);
            dao.insert(addModule);
            dao.insert(editModule);
            dao.insert(delModule);

            //新增超级管理员权限
            condition = String.format("code = '%s' or code = '%s' or code = '%s' or code = '%s'", listModule.getCode(), addModule.getCode(), editModule.getCode(), delModule.getCode());
            list = dao.getListByCondition(condition);
            for (Module module : list) {
                Rolemodule rm = new Rolemodule();
                rm.setMenuid(module.getId());
                rm.setRoleid(1);
                rmDao.insert(rm);
            }
        }
    }


    /**
     * 获取properties文件配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            System.err.print("generator.properties不存在");
            return null;
        }
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix, String autoRemovePre) {
        if ("true".equals(autoRemovePre)) {
            tableName = tableName.substring(tableName.indexOf("_") + 1);
        }
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }

        return columnToJava(tableName);
    }

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }
}
